<template>
  <div ref="rootRef" class="slider">
    <!-- 轮播图的图片内容 -->
    <div class="slider-group">
      <div v-for="item in sliders"
           :key="item.id"
           class="slider-page">
        <a :href="item.link">
          <img :src="item.pic" alt="">
        </a>
      </div>
    </div>
    <!-- 轮播图的图片对应的指示器 -->
    <div class="dots-wrapper">
        <span
          v-for="(item,index) in sliders"
          :key="item.id"
          :class="{'active': currentPageIndex === index }"
          class="dot"
          @click="goPage(index)">
        </span>
    </div>
  </div>
</template>

<script>

import { onMounted, ref } from 'vue'
import useSlider from './use-slider'

export default {
  name: 'Slider',

  // 自定义属性
  props: {
    sliders: {
      type: Array,
      // 数组默认值
      default: () => []
    }
  },
  setup () {
    const rootRef = ref(null)
    /**
     * 这里为什么不把 rootRef.value 传入到useSlider中?  rootRef.value ==> 当前组件DOM结构
     * 而在setup选项中, 要远远早于created、mounted钩子函数
     * 所以这个时候, rootRef.value === undefined, 拿不到dom
     * 想要在setup中拿到dom元素, 必须在 onMounted 钩子函数里面
     */
    const { currentPageIndex } = useSlider(rootRef)
    const { slider } = useSlider(rootRef)

    // todo 点击指示器, 跳往指定的图片 待优化!!!
    const goPage = (index) => {
      console.log('点击了指示器', index)
      // currentPageIndex.value = index
      slider.value.goToPage(index, 0)
      const page = slider.value.getCurrentPage()
      currentPageIndex.value = page.pageX
    }

    return {
      rootRef,
      currentPageIndex,
      goPage,
    }
  }
}
</script>

<style lang="scss" scoped>
.slider {
  min-height: 1px;
  font-size: 0;
  touch-action: pan-y;

  .slider-group {
    // 子绝父相
    position: relative;
    // 轮播图溢出显示效果, 一定要设置 hidden 隐藏
    overflow: hidden;
    // 如何处理元素内的空白 ?
    white-space: nowrap;

    .slider-page {
      display: inline-block;
      transform: translate3d(0, 0, 0);
      backface-visibility: hidden;

      a {
        display: block;
        width: 100%;
      }

      img {
        display: block;
        width: 100%;
      }
    }
  }

  .dots-wrapper {
    position: absolute;
    left: 50%;
    bottom: 12px;
    line-height: 12px;
    transform: translateX(-50%);

    .dot {
      display: inline-block;
      margin: 0 4px;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background-color: $color-text-l;

      &.active {
        width: 20px;
        border-radius: 5px;
        background: $color-text-ll;
      }
    }
  }
}
</style>
